#!/usr/local/php/bin/php
<?php
	define("MYSQLSERVER","10.245.75.74");
	define("MYSQLPORT",3306);
	define("USERNAME","root");
	define("PASSWORD","");

function Usage($argv)
{
	printf("usage:\n\t%s <rec|cmt> <key> <value> <type>\n",$argv[0]);
	printf("example:\n\t%s rec msg_id:create_time:cmt_id cmt_id 2:3:4\n",$argv[0]);
}

function main($argv)
{
	if(count($argv)<5){
		Usage($argv);
		exit(1);
	}

	if($argv[1]=="rec"){
		$db_prefix	= "db2_record_0_";
		$tb_prefix	= "t_record_";
	}else if($argv[1]=="cmt"){
		$db_prefix	= "db2_comment_0_";
		$tb_prefix	= "t_comment_";
	}else{
		printf("<%s> => <rec|cmt>\n",$argv[1]);
		Usage($argv);
		exit(1);
	}

	// 分析输入的参数并构造查询语句及输出数据结构
	// 要查询的字段数组
	$fieldarr	= explode(":",$argv[2]);
	$fieldcount	= count($fieldarr);
	$fieldarr[$fieldcount]	= "content";
	$fieldcount	= $fieldcount+1;
	$fieldarr[$fieldcount]	= "poi_id";
	$fieldcount	= $fieldcount+1;
	$fieldarr[$fieldcount]	= "type";
	$fieldcount	= $fieldcount+1;
	// 重复字段在字段数组中的编号
	$fieldrepeat	= -1;
	// 要查询的字段，以【,】分隔
	$fieldlist	= "";
	for($i=0;$i<$fieldcount;++$i)
	{
		if($i==0)
			$fieldlist	= $fieldarr[$i];
		else
			$fieldlist	= $fieldlist.",".$fieldarr[$i];

		if($fieldarr[$i]==$argv[3])
			$fieldrepeat	= $i;
	}

	if($fieldrepeat<0){
		printf("repeat key error\n");
		Usage($argv);
		exit(1);
	}

	// where查询条件数组
	$wherearr	= explode(":",$argv[4]);
	$wherelist	= "";
	for($i=0;$i<count($wherearr);++$i)
	{
		if($i==0)
			$wherelist	= "type=".$wherearr[$i];
		else
			$wherelist	= $wherelist." or type=".$wherearr[$i];
	}

	$db_server=MYSQLSERVER.":".MYSQLPORT;
	$db_conn=mysql_connect($db_server,USERNAME,PASSWORD);

	for($i=0;$i<10;++$i)
	{
		$db_name=$db_prefix.$i;
		mysql_select_db($db_name,$db_conn);
		for($j=0;$j<100;++$j)
		{
			$tb_name	= $tb_prefix.$j;
			$sql		= "select $fieldlist from $tb_name where $wherelist";
			$result		= mysql_query($sql);
			if(!$result){
				$message	=  "Invalid query: ".mysql_error()."\n";
				$message 	.= "sql: ".$sql;
				die($message);
			}

			$trimsize=strlen("<img-block>");
			while($row=mysql_fetch_row($result))
			{
				$data="";
				for($n=0;$n<$fieldcount-3;++$n)
				{
					if($n==0){
						$data=$row[$n];
					}else{
						$data=$data."-".$row[$n];
					}
				}

				if($row[$fieldcount-1]!=11)
				{
					$content	= $row[$fieldcount-3];
					$first		= strpos($content,"<img-block>");
					$last		= strrpos($content,"<img-block>");	
					if(($last-$first)<=$trimsize)
						continue;

					if($row[$fieldcount-1]==0)
						continue;
				}

				$data=$data." ".$row[$fieldrepeat];
				//printf("last = [%d] first = [%d] %s\n",$last,$first,$data);
				printf("%s\n",$data);
			}

			mysql_free_result($result);
		}
	}

	mysql_close($db_conn);
}

main($argv);
